package org.apimgr.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by yangjie on 2017/9/7.
 * 响应工具类
 */
public class ResponseUtil {

    /**
     * 下载
     * @param file
     * @param response
     * @return
     */
    public static boolean download(File file, HttpServletResponse response) {
        BufferedInputStream fis = null;
        OutputStream toClient = null;
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));

            fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            toClient = response.getOutputStream();
            toClient.write(buffer);
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        } finally {
            try {
                toClient.flush();
                toClient.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
